package com.example.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

/**
 * 跨域请求的配置信息，也可以在application.yml中进行配置
 *
 * */
@Configuration
public class CorsConfig {

    @Bean
    public CorsWebFilter corsWebFilter(){
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
        //允许cookies跨域
        corsConfiguration.setAllowCredentials(true);
        //允许向该服务器提交请求的URI，*表示全部允许
        corsConfiguration.addAllowedOrigin("*");
        //允许访问的头信息，*表示全部
        corsConfiguration.addAllowedHeader("*");
        //预检请求的缓存时间(秒),即在这个时间段里，对应相同的跨域请求不会在预检
        corsConfiguration.setMaxAge(18000L);
        //允许提交请求的方法，*表示全部允许
        corsConfiguration.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsWebFilter(source);
    }
}
